import React, {memo} from 'react'
import {Layout, Menu} from 'antd'
import {history, connect, useModel} from 'umi'
import styles from './styles/index.less'
import {GlobalState} from '@/models/global'
import {setCookie} from '@/utils/cookie'

export interface SiderProps {
	global: GlobalState
	systemName: string
	user: any
	dispatch: any
}
const Sider = memo(({global, dispatch, systemName, user}: SiderProps) => {
	const {initialState, setInitialState} = useModel('@@initialState')
	const {headerMenuKey} = initialState || {}
	const siderMenu = user?.menuTree?.filter(
		(item: {name: any}) => item.name === headerMenuKey,
	)[0]?.children
	/**
	 * @description: 渲染菜单栏
	 * @param {MenuTree} head 当前菜单配置指针
	 * @param {string} keys 当前keys集合
	 * @return {JSX.Element[]} 菜单元素
	 */
	function renderMenu(head = siderMenu) {
		return head?.map((menuItem: any) => {
			if (!menuItem.children) {
				return (
					<Menu.Item
						key={menuItem.name}
						onClick={() => {
							setInitialState(() => ({
								...initialState,
								permission: menuItem?.permission?.toString(),
							}))
							setCookie('permission', menuItem?.permission, 7)
							// history.push({menuItem.path || ''});
							history.push({
								pathname: menuItem.path,
								state: menuItem?.permission?.toString(),
							})
						}}>
						{menuItem.name}
					</Menu.Item>
				)
			}
			return (
				<Menu.SubMenu
					title={menuItem.name}
					key={menuItem.name}
					onTitleClick={() => {
						dispatch({
							type: 'global/updateState',
							payload: {
								openKeys: [menuItem.name],
							},
						})
					}}>
					{renderMenu(menuItem.children)}
				</Menu.SubMenu>
			)
		})
	}
	return (
		<Layout className={styles.sider}>
			<Layout.Header className="header">
				<div className="title">{systemName}</div>
			</Layout.Header>
			<Layout.Content className="content">
				<Menu mode="inline" className="menu">
					{renderMenu()}
				</Menu>
			</Layout.Content>
		</Layout>
	)
})
export default connect(({global, user}: any) => ({
	global,
	user,
}))(Sider)
